package com.atech.ebayadmin.system.dao.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;

import com.atech.ebayadmin.common.pager.Pager;
import com.atech.ebayadmin.common.util.BaseDAOHibernate;
import com.atech.ebayadmin.system.dao.IUserDAO;
import com.atech.ebayadmin.system.model.User;

public class UserDAO extends BaseDAOHibernate implements IUserDAO{
	@Override
	protected Class getObjClass() {
		return User.class;
	}
	public List<User> listUser(String userName, Pager pager) throws Exception{
		StringBuilder queryCountHql = new StringBuilder(this.queryCountHql(userName));	
		StringBuilder queryListHql = new StringBuilder(this.queryListHql(userName));
		Query queryCount = super.getSession().createQuery(queryCountHql.toString());
		Query queryList = super.getSession().createQuery(queryListHql.toString());
		int i =0;
		if(StringUtils.isNotBlank(userName)){
			queryCount.setString(i, userName);
			queryList.setString(i, userName);
			i++;
		}
		Number total = (Number)queryCount.uniqueResult();
		pager.setTotalRows(total.intValue());
		queryList.setFirstResult(pager.getStartRow());
		queryList.setMaxResults(pager.getPageSize());
		return queryList.list();
	}

	private String queryCountHql(String userName){
		StringBuilder sb = new StringBuilder();
		sb.append("select count(*) from ");
		sb.append(getObjClass().getName().toString());
		sb.append(this.createHqlString(userName));
		return sb.toString();
	}
	private String queryListHql(String ebayAct){
		StringBuilder sb = new StringBuilder();
		sb.append("from ");
		sb.append(getObjClass().getName().toString());
		sb.append(this.createHqlString(ebayAct));
		return sb.toString();
	}
	private String createHqlString(String userName){		
		StringBuilder sb = new StringBuilder();
		sb.append(" t where 1=1 ");
		if(StringUtils.isNotBlank(userName)){
			sb.append(" and t.userName = ?");
		}
		sb.append(" and t.isDeleted = 0 order by t.userName desc");
		return sb.toString();
	}
	public Integer saveUser(User po) throws Exception{
		try {
			validateUniqueUser(po);
			Object key = super.getHibernateTemplate().save(po);
			return (Integer) key;
		}catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
	}
	public User getUser(String userName) throws Exception{
		StringBuilder sb = new StringBuilder();
		sb.append("from User t where t.userName = '").append(userName.trim()).append("' and t.isDeleted = 0");
		Query query = super.getSession().createQuery(sb.toString());
		List queryList = query.list();
		if(queryList != null && queryList.size() >0){
			return (User)queryList.get(0);
		}
		return null;
	}
	public void updateUser(User po) throws Exception{
		super.updateObject(po);
	}
	public void delUserAndEbayact(Integer userId) throws Exception{
		StringBuilder sb = new StringBuilder();
		sb.append("delete from UserAndEbayact t where t.userId = ").append(userId);
		Query query = super.getSession().createQuery(sb.toString());
		query.executeUpdate();
	}
	public User getUser(Integer id) throws Exception{
		return (User)super.getHibernateTemplate().get(User.class, id);
	}
	
	// Add for validation user unique in db begin
	public void validateUniqueUser(User po) throws Exception{
		String errorMsg = "";

		System.err.println("[MerchandiseDAO].[validateDuplicateKey].po = " + po);
		if(null != po.getUserName()){
			StringBuilder sb = new StringBuilder();
			sb.append("select count(*) from ");
			sb.append(getObjClass().getName().toString());
			sb.append(" t where 1=1 ");
			sb.append("and t.").append("userName").append(" = ?");
			System.err.println("SQL = " + sb.toString());
			Query queryCount = null;
			Session sqlSession = null;
			Number total = null;
			try {
				sqlSession = this.getHibernateTemplate().getSessionFactory().openSession();
				queryCount = sqlSession.createQuery(sb.toString());
				queryCount.setString(0, po.getUserName().trim());
				total = (Number)queryCount.uniqueResult();
			} catch (Exception e) {
				throw e;
			} finally {
				sqlSession.close();
			}

			System.err.println("total = " + total.intValue());
			/*if(total.intValue() >0 ){
				errorMsg = " 用户："+po.getUserName() + " 已存在, 请重新选择用户名!";
			}*/
			/**
			 * Dec 24, 2012. By Doug.
			 * Above logic revised becoz of following issue: even a user has been deleted, re-adding the same username would prompt " 已存在, 请重新选择用户名!"
			 * Here getIsDeleted()==0 means the original user is NOT deleted yet.
			 */
			System.err.println("userName is = " + po.getUserName());
			System.err.println("userId is = " + po.getUserId());
			if(total.intValue() >0 && 
					null != this.getUser(po.getUserName()) &&
					this.getUser(po.getUserName()).getIsDeleted()==0){
				errorMsg = " 用户："+po.getUserName() + " 已存在, 请重新选择用户名!";
			}
			
		}

		if(StringUtils.isNotBlank(errorMsg)){
			throw new Exception(errorMsg);
		}
	}
	// Add for validation user unique in db end
}
